package com.treetao.union.mall.api.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.treetao.union.core.util.FileUploadService;
import com.treetao.union.db.model.vo.RestResponse;
import com.treetao.union.mall.api.config.DevMFileConfig;

/**
 * 文件上传
 */
@RestController
@RequestMapping("file")
public class FileController {
	@Autowired
	private DevMFileConfig config;
	@Autowired
	private FileUploadService fileUploadService;
    
    @PostMapping("upload")
    public RestResponse uploadFile(HttpServletRequest request,@RequestParam("file") MultipartFile file) throws IOException {

        if(file == null){
            return RestResponse.failure("上传文件为空 ");
        }
       
		String url = fileUploadService.upload(file,config.getSaveFileRootPath(),config.getWebprefix());
        return RestResponse.success().setData(url);
    }


    /**
     * 批量上传图片
     * @param file
     * @return
     * @throws IOException 
     */
    @PostMapping("uploadBatch")
    @ResponseBody
    public RestResponse uploadBatch(@RequestParam("files") MultipartFile[] files) throws IOException {
        if(files == null || files.length == 0){
            return RestResponse.failure("上传文件为空 ");
        }
        List<String> data = Lists.newArrayList();
        for (int i=0;i<files.length;i++) {
        	String url = fileUploadService.upload(files[i],config.getSaveFileRootPath(),config.getWebprefix());
            data.add(url);
        }
        return RestResponse.success(data);
    }

}
